package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Document;
import com.kaishengit.entity.Employee;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.PageUtil;
import com.kaishengit.util.RowMapper;

public class DocumentDao {
	private DBHelp<Document> db = new DBHelp<Document>();
	
	

	public void save(Document d) {
		final String sql = "INSERT INTO t_document(id, title, content, createtime, employeeid, projectid) VALUES(?,?,?,?,?,?)";
		db.executeSQL(sql, d.getId(), d.getTitle(), d.getContent(), d.getCreatetime(), d.getEmployeeid(), d.getProjectid());
	}

	public PageUtil<Document> findAllByProjectId(PageUtil<Document> page, String projectid) {
		final String sql = "SELECT td.id,title, content, td.createtime,employeeid, projectid,te.username FROM t_document AS td LEFT JOIN t_employee AS te ON employeeid = te.id WHERE projectid = ? order by td.createtime desc limit ?,?";
		List<Document> list = db.executeQueryForList(sql, new DocumentRowMapper(), projectid,page.getOffSet(),page.getPageSize());
		page.setResult(list);
		return page;
	}
	
	private class DocumentRowMapper implements RowMapper<Document> {

		public Document mapRow(ResultSet rs) throws SQLException {
			Document d = new Document();
			d.setCreatetime(rs.getString("createtime"));
			d.setEmployeeid(rs.getString("employeeid"));
			d.setId(rs.getString("id"));
			d.setProjectid(rs.getString("projectid"));
			d.setTitle(rs.getString("title"));
			d.setContent(rs.getString("content"));
			
			Employee e = new Employee();
			e.setId(rs.getString("employeeid"));
			e.setUsername(rs.getString("username"));
			d.setEmployee(e);
			return d;
		}
		
	}

	public Document findById(String id) {
		final String sql = "SELECT td.id,title, content, td.createtime,employeeid, projectid,te.username FROM t_document AS td LEFT JOIN t_employee AS te ON employeeid = te.id WHERE td.id = ?";
		return db.executeQueryForObject(sql, new DocumentRowMapper(), id);
	}

	public void edit(String title, String content, String id) {
		final String sql = "UPDATE t_document SET title = ?,content = ? WHERE id = ?";
		db.executeSQL(sql, title, content, id);
	}

	public void del(String id) {
		final String sql = "DELETE FROM t_document WHERE id = ?";
		db.executeSQL(sql, id);
	}

	public Long getCount() {
		final String sql = "select count(*) from t_document";
		return (Long) db.executeQueryForFunctions(sql);
	} 
	
}
